package com.thundern.tdcrawler.selector;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Node;
import org.jsoup.nodes.TextNode;
import org.jsoup.select.Elements;

public class CssSelector extends BaseElementSelector{

	private String selectorText;
	
	private String attrName;
	
	public CssSelector(String selectorText) {
		this.selectorText = selectorText;
	}
	
	public CssSelector(String seletorText, String attrName) {
		this.selectorText = seletorText;
		this.attrName = attrName;
	}
	
	public String getValue(Element element) {
		if (attrName == null) {
            return element.outerHtml();
        } else if ("innerHtml".equalsIgnoreCase(attrName)) {
            return element.html();
        } else if ("text".equalsIgnoreCase(attrName)) {
            return getText(element);
        } else if ("allText".equalsIgnoreCase(attrName)) {
            return element.text();
        } else {
            return element.attr(attrName);
        }		
	}
	
	String getText(Element element) {
		StringBuilder nodeStringBuffer = new StringBuilder();
		for(Node node : element.childNodes()) {
			if(node instanceof TextNode) {
				TextNode textNode = (TextNode)node;
				nodeStringBuffer.append(textNode.text());
			}
		}
		return nodeStringBuffer.toString();
	}
	
	public String select(Element element) {
		List<Element> elements = selectElements(element);
		if(CollectionUtils.isEmpty(elements)) {
			return null;
		}
		return getValue(elements.get(0));
	}
	
	public List<String> selectList(Element element) {
		List<String> strings = new ArrayList<String>();
		List<Element> elements = selectElements(element);
		if(CollectionUtils.isNotEmpty(elements)) {
			for(Element ele : elements) {
				String value = getValue(ele);
				if(null != value) strings.add(value);				
			}
		}		
		return strings;
	}
	
	public Element selectElement(Element element) {
		Elements elements = element.select(selectorText);
		if(CollectionUtils.isNotEmpty(elements)) {
			return elements.get(0);
		}
		return null;
	}
	
	public List<Element> selectElements(Element element) {
		return element.select(selectorText);
	}

	public boolean hasAttribute() {
		return attrName != null;
	}

}
